package gx.web.controller;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import gx.entity.Product;
import gx.entity.Category;
import gx.entity.Manager;
import gx.entity.Purchase;
import gx.entity.PurchaseItem;
import gx.entity.Supplier;
import gx.entity.Warehouse;
import gx.entity.common.Page;
import gx.service.CategoryService;
import gx.service.ProductService;
import gx.service.PurchaseItemService;
import gx.service.PurchaseService;
import gx.service.StoreService;
import gx.service.SupplierService;
import gx.service.WarehouseService;


@Controller
@RequestMapping("/mng/purc")
public class PurchaseController {

	@Autowired
	private PurchaseService purchaseService;

	@Autowired
	private SupplierService supplierService;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private ProductService productService;
	
	@Autowired
	private PurchaseItemService purchaseItemService;
	
//	@Autowired
//	private StoreService storeService;
	

	// 采购订单列表（status 0 （草稿） 1（已下单））
	@RequestMapping("/list.jhtml")
	public ModelAndView find(@RequestParam(name = "size", defaultValue = "10") int size,
			@RequestParam(name = "number", defaultValue = "1") int number) {
		ModelAndView mav = new ModelAndView("/mng/purc/list");
		Page<Purchase> page = purchaseService.findByStatus(size, number, 0, 1,2);
		mav.addObject("page", page);
		return mav;
	}
//	@RequestMapping("/getlist.jhtml")
//	public ModelAndView find2(@RequestParam(name = "size", defaultValue = "10") int size,
//			@RequestParam(name = "number", defaultValue = "1") int number) {
//		ModelAndView mav = new ModelAndView("/mng/purc/list");
//		Page<Purchase> page = purchaseService.findByStatus(size, number, 2,3);
//		mav.addObject("page", page);
//		return mav;
//	}

	// 预加载添加页面数据
	@RequestMapping("/toAdd.jhtml")
	public ModelAndView toAdd() {
		ModelAndView mav = new ModelAndView("/mng/purc/add");
		// 供应商
		List<Supplier> supList = supplierService.findAll();
		mav.addObject("supList", supList);

		

		// 商品分类
		List<Category> cateList = categoryService.findAll();
		mav.addObject("cateList", cateList);

		// sn序列号
		StringBuffer sb = new StringBuffer("CG");
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		mav.addObject("sn", sb.append(sdf.format(date)).toString());

		return mav;
	}

	//增加采购订单
	@RequestMapping("/add.jhtml")
	public String add(int pay_type, String pur_date, String remark, String sn,
			Integer supp_id, Integer[] p_id, Integer[] p_num,
			BigDecimal[] sale_price, HttpSession session) throws ParseException {

		Manager mgr = (Manager) session.getAttribute("curr_mgr"); // 制单人信息

		Purchase purc = new Purchase(); // 采购订单项
		purc.setManager(mgr);
		purc.setPay_type(pay_type); // 支付类型 0:全款 1:欠款
		if (pur_date != null && !"".equals(pur_date)) {
			purc.setPur_date(new SimpleDateFormat("yyyy-MM-dd").parse(pur_date));
		}
		purc.setRemark(remark); // 备注
		purc.setSn(sn); // 采购订单编号
		purc.setStatus(0); // 默认为草稿
		purc.setSupplier(supplierService.load(supp_id)); // 设置所属的供应商
		                                 
		// 采购项
		ArrayList<PurchaseItem> items = new ArrayList<PurchaseItem>();

		int length = p_id == null ? 0 : p_id.length; // 采购订单项
		for (int i = 0; i < length; i++) {
			Integer id = p_id[i];//采购项p_id
			PurchaseItem item = new PurchaseItem(); // 采购订单项对象
			item.setNum(p_num[i]); // 数量
			item.setPrice(sale_price[i]); // 价格//总价格
			item.setProduct(productService.load(id)); // 设置所属商品
			item.setPurchase(purc); // 隶属采购订单

			boolean exists = false;
			for (PurchaseItem temp : items) {
				if (id.intValue() == temp.getProduct().getId().intValue()) {
					temp.setNum(temp.getNum() + p_num[i]);
					exists = true;
					break;
				}
			}

			if (!exists) {
				items.add(item);
			}
		}
		purc.setItemList(items);
		// 计算总价
		BigDecimal totals = new BigDecimal(0);
		for (PurchaseItem temp : items) {
			totals = totals.add(temp.getPrice().multiply(
					new BigDecimal(temp.getNum())));
		}
		purc.setCost(totals); // 采购订单中总额
		purchaseService.save(purc);
		return "redirect:/mng/purc/list.jhtml";
	}

	// 下单功能
	@RequestMapping("/place.jhtml")
	public String place(Integer id) {
		Purchase purchase = purchaseService.get(id);
		purchase.setStatus(1);// 状态已下单
		purchaseService.update(purchase);
		return "redirect:/mng/purc/list.jhtml";
	}

	
	
	// 入库功能
		@RequestMapping("/ruku.jhtml")
		public String ruku(Integer id) {
			Purchase purchase = purchaseService.get(id);
			purchase.setStatus(2);// 状态已入库
			//System.out.println("已入库");
			purchaseService.update(purchase);
			//采购项
		List<PurchaseItem> items=purchaseItemService.findByPurId(id);
		int oldnum;//商品表中的原来数量
		int newnum;//入库后的新数量
	//	Date expirDate;//过期日期
		int expirTime;//保质期
		Integer[] p_id = new Integer[items.size()];
		Integer[] p_num = new Integer[items.size()];
		for(int i=0;i<items.size();i++){
			p_id[i] = items.get(i).getProduct().getId();
			p_num[i] = items.get(i).getNum();
			//expirTime[i]=purchase.getPur_date();
			//Integer pid = p_id[i];
			//库存数量
			Product product = productService.get(p_id[i]);
			oldnum=product.getNum();
			newnum=oldnum+p_num[i];
			product.setNum(newnum);
			//过期时间
			expirTime=product.getExpireTime();
		//Date	expirDate=getAfterDate(purchase.getPur_date(),expirTime);//如何加保质期天？
			Date expirDate=purchaseService.getAfterDate(purchase.getPur_date(), expirTime);
			product.setExpir_date(expirDate);
			productService.update(product);
		
		}
		return "redirect:/mng/purc/list.jhtml";
	}

			
	
		
		
	// 退货功能
//		@RequestMapping("/tuihuo.jhtml")
//		public String tuihuo(Integer id) {
//			Purchase purchase = purchaseService.get(id);
//			purchase.setStatus(3);// 状态已入库
//			purchaseService.update(purchase);
//			return "redirect:/mng/purc/list.jhtml";
//		}
	
		
	// 删除草稿状态的采购订单
	@RequestMapping("/delete.jhtml")
	public String delete(Integer id) {
		purchaseService.delete(id);
		return "redirect:/mng/purc/list.jhtml";
	}

	// 动态查询  通过状态和日期
	@RequestMapping("/find.jhtml")
	public ModelAndView find(@RequestParam(name = "size", defaultValue = "10") int size,
			@RequestParam(name = "number", defaultValue = "1") int number, Integer status, String startDate,
			String endDate) throws ParseException {
		// 离线查询条件对象 "from Purchase"
		DetachedCriteria dc = DetachedCriteria.forClass(Purchase.class);
		DetachedCriteria dc2 = DetachedCriteria.forClass(Purchase.class);
		DetachedCriteria dc3 = DetachedCriteria.forClass(Purchase.class);

		// "from Purchase where status?"
		if (status != null && status.intValue() >=0) {
			dc.add(Property.forName("status").eq(status)); // eq: 等于
			dc2.add(Property.forName("status").eq(status));
			dc3.add(Property.forName("status").eq(status));
		} else {
			Criterion c = Restrictions.or(Restrictions.eq("status", 0), Restrictions.eq("status", 1),Restrictions.eq("status", 2));
			dc.add(c);
			dc2.add(c);
			dc3.add(c);
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		// "from Purchase where status=? and pur_date>? "
		if (null != startDate && !"".equals(startDate)) {
			dc.add(Property.forName("pur_date").ge(df.parse(startDate)));// ge:大于等于
			dc2.add(Property.forName("pur_date").ge(df.parse(startDate)));
			dc3.add(Property.forName("pur_date").ge(df.parse(startDate)));
		}

		// "from Purchase where status=? and pur_date>? and pur_date<?"
		if (null != endDate && !"".equals(endDate)) {
			dc.add(Property.forName("pur_date").le(df.parse(endDate)));// le:
																		// 小于等于
			dc2.add(Property.forName("pur_date").ge(df.parse(startDate)));
			dc3.add(Property.forName("pur_date").ge(df.parse(startDate)));
		}

		dc.addOrder(Order.desc("id"));
		dc2.setProjection(Projections.count("id"));
		dc3.setProjection(Projections.count("id"));

		Page<Purchase> page = purchaseService.findByCriteria(size, number, dc, dc2,dc3);

		ModelAndView mav = new ModelAndView("/mng/purc/list");
		mav.addObject("page", page);

		return mav;
	}

	// 编辑加载数据功能
	@RequestMapping("/detail.jhtml")
	public ModelAndView detail(Integer id) {
		ModelAndView mav = new ModelAndView("/mng/purc/detail");
		// 获得采购订单
		Purchase purchase = purchaseService.get(id);

		// 采购订单编号
		mav.addObject("sn", purchase.getSn());

		// 供应商
		List<Supplier> supList = supplierService.findAll();
		mav.addObject("supList", supList);
		
		//<%= new Date() %>
		// 商品分类
		List<Category> cateList = categoryService.findAll();
		mav.addObject("cateList", cateList);

		mav.addObject("purchase",purchase);
		
		mav.addObject("pur_list",purchase.getItemList());//采购项List
		return mav;
	}
	
	// 编辑加载数据功能
	@RequestMapping("/detail2.jhtml")
	public ModelAndView detail2(Integer id) {
		ModelAndView mav = new ModelAndView("/mng/purc/detail2");
		// 获得采购订单
		Purchase purchase = purchaseService.get(id);

		// 采购订单编号
		mav.addObject("sn", purchase.getSn());

		// 供应商
		List<Supplier> supList = supplierService.findAll();
		mav.addObject("supList", supList);
		
		
		// 商品分类
		List<Category> cateList = categoryService.findAll();
		mav.addObject("cateList", cateList);

		mav.addObject("purchase",purchase);
		
		mav.addObject("pur_list",purchase.getItemList());//采购项List
		return mav;
	}
	
	//修改功能
    @RequestMapping("/edit.jhtml")
    public String edit(int id,int pay_type, String pur_date, String remark, String sn, 
			Integer supp_id, Integer[] p_id,Integer[] p_num,
			BigDecimal[] sale_price, HttpSession session) throws ParseException{
    	Manager mgr = (Manager) session.getAttribute("curr_mgr"); // 制单人信息

		Purchase purc = purchaseService.get(id); // 或得采购订单项
		purc.setManager(mgr); //制单人
		purc.setPay_type(pay_type); // 支付类型 0:全款 1:欠款
		if (pur_date != null && !"".equals(pur_date)) {
			purc.setPur_date(new SimpleDateFormat("yyyy-MM-dd").parse(pur_date));
		}
		purc.setRemark(remark); // 备注
		purc.setSn(sn); // 采购订单编号
		purc.setStatus(0); // 默认为草稿
		purc.setSupplier(supplierService.load(supp_id)); // 设置所属的供应商

		// 采购项
		ArrayList<PurchaseItem> items = new ArrayList<PurchaseItem>();

		//通过id查询所以采购订单项
		List<PurchaseItem> puritem_list = purchaseItemService.findByPurId(id);
		
		for(int i = 0; i < puritem_list.size();i++){
			
			purchaseItemService.delete(puritem_list.get(i));
			
		}
		int length = p_id == null ? 0 : p_id.length; // 采购订单项
		for (int i = 0; i < length; i++) {
			//删除
			Integer pitem_id = p_id[i];
			PurchaseItem item = new PurchaseItem(); // 采购订单项对象
			item.setNum(p_num[i]); // 数据
			item.setPrice(sale_price[i]); // 价格
			item.setProduct(productService.load(pitem_id)); // 设置所属商品
			item.setPurchase(purc); // 隶属采购订单

			boolean exists = false;
			for (PurchaseItem temp : items) {
				if (pitem_id.intValue() == temp.getProduct().getId().intValue()) {
					temp.setNum(temp.getNum() + p_num[i]);
					exists = true;
					break;
				}
			}

			if (!exists) {
				items.add(item);
			}
		}
		purc.setItemList(items);
		// 计算总价
		BigDecimal totals = new BigDecimal(0);
		for (PurchaseItem temp : items) {
			totals = totals.add(temp.getPrice().multiply(new BigDecimal(temp.getNum())));
		}
		purc.setCost(totals); // 采购订单中总额
		purchaseService.update(purc);
       return "redirect:/mng/purc/list.jhtml";
    }
	

}
